{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9883fb3e-2c86-4bbd-8c9b-29217bf2b141",
   "metadata": {},
   "source": [
    "# Pandas\n",
    "- Pandas是整个数据分析的核心操作，之前学习的Numpy也只是Pandas的基础。即后续的数据清洗，数据规约，数据统计计算等操作，都需要Pandas. 他也是一个强大的数据分析库的唯一的库\n",
    "## Pandas概述\n",
    "- Pandas是基于BSD许可的开源支持库，为Python提供了高性能，易事用的数据结构与数据分析工具，Pandas是Python的核心数据分析支持库，提供了快捷、灵活、明确的数据结构，旨在简单、直观地处理关系型、标记型数据。Pandas的目标是成为Python数据分析实践或实战的必备高级工具，其长远目标是称为最强大、最灵活，可以支持任何语言的开源数据分析工具。\n",
    "## Pandas可以做什么？\n",
    "- Pandas适用于处理多种类型的数据\n",
    " - 与SQL或Excel表类似的，包含异构列的表格数据\n",
    " - 有序和无序（非固定频率）的时间序列数据\n",
    " - 带行标签的矩阵数列，包括同构或异构型数据\n",
    " - 任意其他形式的观测，统计数据集，数据传入Pandas数据结构时不必事先标记\n",
    "- Pandas的主要的数据结构是Series(一维数据)与DataFrame(二维数据)，这两种数据结构是以处理金融、统计、社会科学、工程等领域里的大多数典型用例，对于R用户、DataFrame提供了大量丰富的功能，Pandas基于Numpy开发，可以与其他第三方科学计算支持库完美集成\n",
    "## 使用Pandas的原因\n",
    "- 自动处理浮点与非浮点数据里的缺失数据\n",
    "- 大小可变、插入或删除DataFrame等多维对象的列\n",
    "- 自动、显示数据对齐，显示的将对象与一组标签对齐，也可以忽略标签，在Series、DataFrame计算时自动与数据对齐\n",
    "- 强大、灵活的分组(group by)功能：拆分-应用-组合数据集，聚合、转换数据\n",
    "- 把Python和Numpy数据结构里不规则、不同索引的数据轻松的转换为DataFrame对象\n",
    "- 基于智能标签，对大型数据集进行切片、花式索引、子集分解等操作\n",
    "- 直观地合并(merge): 【连接(join)】数据集\n",
    "- 灵活地重塑(reshape): 【透视(pivot)】数据集\n",
    "- 轴支持结构化标签：一个刻度支持多个标签\n",
    "- 成熟的Io工具：读取文本文件（CSV等支持分隔符的文件）、Excel文件、数据库等来源的数据，利用超快的HDF5格式保存/加载数据\n",
    "- 时间序列：支持日期范围生成、频率转换、移动窗口统计、统计窗口线性回归、日期位移等时间序列功能\n",
    "##### 这些功能主要是为了解决实际问题，科研环境的痛点，处理数据一般分为几个阶段：数据整理与清晰、数据分析与建模、数据可视化与制表，Pandas是处理数据的理想工具\n",
    "- Pandas速度很快，底层是statmodels的依赖项\n",
    "\n",
    "## Pandas库的导入\n",
    "- 通常Pandas和Numpy库一同使用，导入方法：\n",
    "- import pandas as pd\n",
    "- import numpy as np\n",
    "## Pandas的数据结构\n",
    "- 要使用pandas, 首先必须要熟悉两个主要的数据结构：Series和DataFrame\n",
    "- Series，维度=1， 该结构能存储各种数据类型，比如字符串、整数、浮点数、Python对象等，Series用name和index属性来描述数据值。Series是一维数组，因此其维度不可以改变\n",
    "- DataFrame, 维度=2，DataFrame是一种二维【表格】型数据的结构，既有行索引，也有列索引。行索引是index,列索引是columns.在创建该结构时，可以指定相应的索引值。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76fba0ec-05af-4d92-9e47-cbd8ee476832",
   "metadata": {},
   "source": [
    "### Series数据结构\n",
    "- Series类似于一维数组，被numpy的array接近，由一组数据和数据标签组成，数据标签有索引的作用。数据标签是pandas区分于numpy的重要特征，调用 pd.Series 函数即可\n",
    "- pandas.Series(data, index, dtype, copy)\n",
    "- data: 为Python中的字典、多维数组、标量值（比如：5）\n",
    "- index: 轴标签列表\n",
    "- dtype: 数据类型，如果没有提供，则会自动判断得出\n",
    "- copy: 对data进行拷贝，默认为False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2dfdf05c-abb6-473d-915f-0e68b0958cd2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b    1\n",
      "a    0\n",
      "c    2\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "d = {'b':1, 'a':0, 'c':2}\n",
    "s = pd.Series(d)\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05351358-741f-48fe-8568-f1c1757c0a41",
   "metadata": {},
   "source": [
    "创建一个空的Series对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "fd7e1dba-63e8-4510-bb2c-f639909f7277",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Series([], dtype: object)\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "#输出数据为空\n",
    "s = pd.Series()\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ec78905-b688-4df9-9bc0-62ac8a64d2cc",
   "metadata": {},
   "source": [
    "- ndarray创建Series对象\n",
    "- ndarray是Numpy中的数据类型，当data是array时，出安迪的索引必须具有与数组相同的长度。假设没有给index参数传参，在默认的情况，索引值将使用的是"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c59bd3aa-cc6a-4779-b7d9-60c4a6cba672",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    a\n",
      "1    b\n",
      "2    c\n",
      "3    d\n",
      "dtype: object\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "data = np.array(['a','b','c','d'])\n",
    "s = pd.Series(data)\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bf40e20-5525-4e69-83f2-c952754ef1a9",
   "metadata": {},
   "source": [
    "上述例子中，没有传递任何的传递任何的索引，所以索引默认从0开始分配，其索引范围为0到len(data)-1, 即0到3，这种设置方式被称为“隐式索引”"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8db3c912-8cab-437b-bc44-199722b8786b",
   "metadata": {},
   "source": [
    "使用 【显式索引】定义索引标签"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c3736750-ed8b-4b3b-b26c-230dbf78df49",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1    a\n",
      "2    b\n",
      "3    c\n",
      "4    d\n",
      "dtype: object\n",
      "100    a\n",
      "101    b\n",
      "102    c\n",
      "103    d\n",
      "dtype: object\n",
      "I      a\n",
      "II     b\n",
      "III    c\n",
      "IV     d\n",
      "dtype: object\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "data = np.array(['a','b','c','d'])\n",
    "#自定义索引标签（即显式索引）\n",
    "s = pd.Series(data, index=[1,2,3,4])\n",
    "print(s)\n",
    "\n",
    "s1 = pd.Series(data, index=[100,101,102,103])\n",
    "print(s1)\n",
    "\n",
    "s2 = pd.Series(data, index=['I','II','III','IV'])\n",
    "print(s2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa9c00a5-0cef-40cc-8e70-7df7550814ac",
   "metadata": {},
   "source": [
    "使用dict字典创建Series对象，同时为index传递索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "95604ce5-d7b6-4eec-b73f-10b3f879e76a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b    1.0\n",
      "c    2.0\n",
      "d    NaN\n",
      "a    0.0\n",
      "dtype: float64\n",
      "I     NaN\n",
      "II    NaN\n",
      "III   NaN\n",
      "IV    NaN\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "data = {'a':0., 'b':1., 'c':2.}\n",
    "s = pd.Series(data, index=['b', 'c', 'd', 'a'])\n",
    "print(s)\n",
    "\n",
    "s1 = pd.Series(data, index=['I', 'II', 'III', 'IV'])\n",
    "print(s1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "395d8bfe-1e02-4265-a368-196473400bc0",
   "metadata": {},
   "source": [
    "当传递的索引值无法找到与其对应的值时，使用NaN(非数字)填充"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf9ad89b-acef-404d-a6e1-5be10c0614a2",
   "metadata": {},
   "source": [
    "使用标量创建Series对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "94bb038c-74cd-4a53-85f9-be04c8b526f0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    5\n",
      "1    5\n",
      "2    5\n",
      "3    5\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "s = pd.Series(5, index=[0, 1, 2, 3])\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "197b29f5-8240-4e6e-ac07-527463d925b4",
   "metadata": {},
   "source": [
    "## 访问Series数据\n",
    "- 分为两种方式:1.位置索引访问；2.索引标签访问"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00e69079-1fd0-4276-994c-ef1f0114b98c",
   "metadata": {},
   "source": [
    "1)位置索引访问"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a2875bf4-184c-4219-9905-0b32b542625f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Windows\\Temp\\ipykernel_22580\\3175552974.py:4: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
      "  print(s[0])    #位置下标 访问的是1\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "s = pd.Series([1,2,3,4,5], index=['a','b','c','d','e'])\n",
    "print(s[0])    #位置下标 访问的是1\n",
    "print(s['a'])    #标签下标 访问的是1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57f8a92a-de62-44ba-bb0d-727646a191ee",
   "metadata": {},
   "source": [
    "通过切片的方式访问Series序列中的数据:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "02ed9c43-ba33-4d54-8a1c-bb2fc4553ca6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1\n",
      "b    2\n",
      "c    3\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "s = pd.Series([1,2,3,4,5], index=['a','b','c','d','e'])\n",
    "print(s[:3])    #取前3个"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4851d20-7214-44d7-b813-7519d08285b6",
   "metadata": {},
   "source": [
    "如果想要获取最后三个元素，也可以通过切片:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3e05414c-0d41-46d4-ba6c-c1d5b641d5a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "c    3\n",
      "d    4\n",
      "e    5\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "s = pd.Series([1,2,3,4,5], index=['a','b','c','d','e'])\n",
    "print(s[-3:])    #取最后3个"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9035254-a0f0-4d20-b92b-0bec88f9cde1",
   "metadata": {},
   "source": [
    "2）索引标签访问\n",
    "Series类似于固定大小的dict,把Index中的索引标签当作key,而把Series序列中的元素值当作value,然后通过"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b522c5a9-48b6-47a3-aeec-acca21c38cdf",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "89b75ba9-51e9-44ba-b334-6bdcfa608029",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "s = pd.Series([6,7,8,9,10], index=['a','b','c','d','e'])\n",
    "print(s['a'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87e865df-7d40-4bb2-a435-bbbfa5ef318e",
   "metadata": {},
   "source": [
    "使用索引标签访问多个元素值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "3be563c9-8ed6-4970-9465-6419d83955aa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    6\n",
      "c    8\n",
      "d    9\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "s = pd.Series([6,7,8,9,10], index=['a','b','c','d','e'])\n",
    "print(s[['a','c','d']])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ec5bfb6-3708-4774-9e1b-0a45f936bd61",
   "metadata": {},
   "source": [
    "如果使用了index中不包含的标签，则会触发异常："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "53cb560f-b43a-455f-b9ba-5b7b460c7873",
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'f'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:3805\u001b[0m, in \u001b[0;36mIndex.get_loc\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m   3804\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m-> 3805\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_engine\u001b[38;5;241m.\u001b[39mget_loc(casted_key)\n\u001b[0;32m   3806\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n",
      "File \u001b[1;32mindex.pyx:167\u001b[0m, in \u001b[0;36mpandas._libs.index.IndexEngine.get_loc\u001b[1;34m()\u001b[0m\n",
      "File \u001b[1;32mindex.pyx:196\u001b[0m, in \u001b[0;36mpandas._libs.index.IndexEngine.get_loc\u001b[1;34m()\u001b[0m\n",
      "File \u001b[1;32mpandas\\\\_libs\\\\hashtable_class_helper.pxi:7081\u001b[0m, in \u001b[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001b[1;34m()\u001b[0m\n",
      "File \u001b[1;32mpandas\\\\_libs\\\\hashtable_class_helper.pxi:7089\u001b[0m, in \u001b[0;36mpandas._libs.hashtable.PyObjectHashTable.get_item\u001b[1;34m()\u001b[0m\n",
      "\u001b[1;31mKeyError\u001b[0m: 'f'",
      "\nThe above exception was the direct cause of the following exception:\n",
      "\u001b[1;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[15], line 4\u001b[0m\n\u001b[0;32m      2\u001b[0m s \u001b[38;5;241m=\u001b[39m pd\u001b[38;5;241m.\u001b[39mSeries([\u001b[38;5;241m6\u001b[39m,\u001b[38;5;241m7\u001b[39m,\u001b[38;5;241m8\u001b[39m,\u001b[38;5;241m9\u001b[39m,\u001b[38;5;241m10\u001b[39m], index\u001b[38;5;241m=\u001b[39m[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124ma\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mb\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mc\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;124m'\u001b[39m\u001b[38;5;124md\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;124m'\u001b[39m\u001b[38;5;124me\u001b[39m\u001b[38;5;124m'\u001b[39m])\n\u001b[0;32m      3\u001b[0m \u001b[38;5;66;03m#不包含f值\u001b[39;00m\n\u001b[1;32m----> 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(s[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m'\u001b[39m])\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\series.py:1121\u001b[0m, in \u001b[0;36mSeries.__getitem__\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m   1118\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_values[key]\n\u001b[0;32m   1120\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m key_is_scalar:\n\u001b[1;32m-> 1121\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_get_value(key)\n\u001b[0;32m   1123\u001b[0m \u001b[38;5;66;03m# Convert generator to list before going through hashable part\u001b[39;00m\n\u001b[0;32m   1124\u001b[0m \u001b[38;5;66;03m# (We will iterate through the generator there to check for slices)\u001b[39;00m\n\u001b[0;32m   1125\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m is_iterator(key):\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\series.py:1237\u001b[0m, in \u001b[0;36mSeries._get_value\u001b[1;34m(self, label, takeable)\u001b[0m\n\u001b[0;32m   1234\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_values[label]\n\u001b[0;32m   1236\u001b[0m \u001b[38;5;66;03m# Similar to Index.get_value, but we do not fall back to positional\u001b[39;00m\n\u001b[1;32m-> 1237\u001b[0m loc \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mindex\u001b[38;5;241m.\u001b[39mget_loc(label)\n\u001b[0;32m   1239\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m is_integer(loc):\n\u001b[0;32m   1240\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_values[loc]\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:3812\u001b[0m, in \u001b[0;36mIndex.get_loc\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m   3807\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(casted_key, \u001b[38;5;28mslice\u001b[39m) \u001b[38;5;129;01mor\u001b[39;00m (\n\u001b[0;32m   3808\u001b[0m         \u001b[38;5;28misinstance\u001b[39m(casted_key, abc\u001b[38;5;241m.\u001b[39mIterable)\n\u001b[0;32m   3809\u001b[0m         \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;28many\u001b[39m(\u001b[38;5;28misinstance\u001b[39m(x, \u001b[38;5;28mslice\u001b[39m) \u001b[38;5;28;01mfor\u001b[39;00m x \u001b[38;5;129;01min\u001b[39;00m casted_key)\n\u001b[0;32m   3810\u001b[0m     ):\n\u001b[0;32m   3811\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m InvalidIndexError(key)\n\u001b[1;32m-> 3812\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mKeyError\u001b[39;00m(key) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01merr\u001b[39;00m\n\u001b[0;32m   3813\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m:\n\u001b[0;32m   3814\u001b[0m     \u001b[38;5;66;03m# If we have a listlike key, _check_indexing_error will raise\u001b[39;00m\n\u001b[0;32m   3815\u001b[0m     \u001b[38;5;66;03m#  InvalidIndexError. Otherwise we fall through and re-raise\u001b[39;00m\n\u001b[0;32m   3816\u001b[0m     \u001b[38;5;66;03m#  the TypeError.\u001b[39;00m\n\u001b[0;32m   3817\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_indexing_error(key)\n",
      "\u001b[1;31mKeyError\u001b[0m: 'f'"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "s = pd.Series([6,7,8,9,10], index=['a','b','c','d','e'])\n",
    "#不包含f值\n",
    "print(s['f'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "613c91de-4c0c-4b27-9046-7efbf6f86d53",
   "metadata": {},
   "source": [
    "### Series常用属性\n",
    "- axes 以列表的形式返回所有行索引标签\n",
    "- dtype 返回对象的数据类型\n",
    "- empty 返回一个空的Series对象\n",
    "- ndim 返回输入数据的维度\n",
    "- size 返回输入数据的元素数量\n",
    "- values 以ndarray的形式返回Series对象\n",
    "- index 返回一个Rangeeindex对象，用来描述索引的取值范围"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e32f1ce1-f971-4004-838f-3947f9939765",
   "metadata": {},
   "source": [
    "创建一个Series对象，使用属性进行操作："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "82747a03-c3b0-400c-b833-fcd0ac86969b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0.552858\n",
      "1    1.373599\n",
      "2   -0.519148\n",
      "3   -0.041806\n",
      "4    1.496498\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "s = pd.Series(np.random.randn(5))\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a7f572f-16da-45fa-95f7-783d435a40b4",
   "metadata": {},
   "source": [
    "上面例子中的行索引标签是[0,1,2,3,4]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18785103-fd36-4cbb-8ad7-cddcea6a4919",
   "metadata": {},
   "source": [
    "以列表的形式返回所有的行索引标签："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "a04c0341-b1cc-4337-b904-c83275cd91c5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[RangeIndex(start=0, stop=5, step=1)]\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "s = pd.Series(np.random.randn(5))\n",
    "print(s.axes)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c71ea67e-e329-435c-a66b-6b5579721053",
   "metadata": {},
   "source": [
    "返回对象的数据类型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "d3b4d3a5-c04e-4e1d-b4f8-975c039ff2b9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "float64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "s = pd.Series(np.random.randn(5))\n",
    "#print(s.axes)\n",
    "print(s.dtype)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa5adddb-f068-460e-9ad4-70b4d3e25f45",
   "metadata": {},
   "source": [
    "判断数据对象是否为空，返回的是布尔值类型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2b452fe0-0b68-4c26-b8d1-33d4aa7d03b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "是否为空对象？\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "s = pd.Series(np.random.randn(5))\n",
    "print(\"是否为空对象？\")\n",
    "print(s.empty)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6fb95d2-c92e-465f-be98-aa6d824cd059",
   "metadata": {},
   "source": [
    "查看序列的维数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d5365bde-6306-4890-a70a-e3b512e85e65",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0.411712\n",
      "1    0.894781\n",
      "2    0.275756\n",
      "3   -0.578423\n",
      "4   -1.263501\n",
      "dtype: float64\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "s = pd.Series(np.random.randn(5))\n",
    "print(s)\n",
    "print(s.ndim)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a39edeac-545b-4c2c-b011-e30122e0379e",
   "metadata": {},
   "source": [
    "返回Series对象的大小："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "70449d6a-a816-4d7c-a178-693bb9c99abf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0   -0.709173\n",
      "1    0.996423\n",
      "2   -0.867265\n",
      "dtype: float64\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "s = pd.Series(np.random.randn(3))\n",
    "print(s)\n",
    "#Series对象的的大小\n",
    "print(s.size)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ae2e4b5-e96c-4512-ba85-b1df22125f39",
   "metadata": {},
   "source": [
    "以数组的方式返回Series对象中的数据："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "46938a65-fcba-4e8e-a810-5b2e317b3dbb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0   -1.063614\n",
      "1   -0.729372\n",
      "2    0.024000\n",
      "3   -0.421716\n",
      "4    0.199578\n",
      "dtype: float64\n",
      "输出Series中数据：\n",
      "[-1.0636135  -0.72937187  0.02400019 -0.42171596  0.199578  ]\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "s = pd.Series(np.random.randn(5))\n",
    "print(s)\n",
    "print(\"输出Series中数据：\")\n",
    "print(s.values)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06f77801-2984-4be8-a7b7-a5ae9c588905",
   "metadata": {},
   "source": [
    "查看Series对象当中属性的取值范围："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "99fccc11-581d-410b-848f-01e518f283b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['a', 'b', 'c', 'd'], dtype='object')\n",
      "RangeIndex(start=0, stop=4, step=1)\n"
     ]
    }
   ],
   "source": [
    "#显式索引\n",
    "import pandas as pd\n",
    "s = pd.Series([1,2,5,8], index = ['a','b','c','d'])\n",
    "print(s.index)\n",
    "\n",
    "#隐式索引\n",
    "s1 = pd.Series([1,2,5,8])\n",
    "print(s1.index)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99317d71-5a6a-4b4e-81ab-82aa88658276",
   "metadata": {},
   "source": [
    "### Series常用方法\n",
    "- head()、tail()查看数据\n",
    "  - 如果要想查看Series的某一部分数据，可以使用head()或tail()方法，其中head()方法返回前n行的数据，默认显示前5行数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8f0178cd-513c-4158-a0ff-6c770d508e75",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数据的内容是： 0    2.180538\n",
      "1    0.555496\n",
      "2    0.072115\n",
      "3   -0.790716\n",
      "4    0.176977\n",
      "dtype: float64\n",
      "0    2.180538\n",
      "1    0.555496\n",
      "2    0.072115\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "s = pd.Series(np.random.randn(5))\n",
    "print(\"数据的内容是：\", s)\n",
    "\n",
    "#打印前3行数据\n",
    "print(s.head(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ad6f375-1389-41b5-8f68-e92be88fda03",
   "metadata": {},
   "source": [
    "如果调用时，不传入任何参数，则默认返回前5行"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22e6b6f2-107f-4a28-9d9a-ecf7f9dd7906",
   "metadata": {},
   "source": [
    "tail()返回的是后n行的数据，默认后5行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "22a5822b-c846-42c9-a07c-11111cb88b42",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0.308470\n",
      "1   -0.865923\n",
      "2    0.615254\n",
      "3   -0.880878\n",
      "dtype: float64\n",
      "------------------\n",
      "2    0.615254\n",
      "3   -0.880878\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "s = pd.Series(np.random.randn(4))\n",
    "print(s)\n",
    "print('------------------')\n",
    "print(s.tail(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7206822e-a7f2-4796-8c01-c2c6d9c0a9a9",
   "metadata": {},
   "source": [
    "- isnull()、notnull()检测缺失值\n",
    "  - isnull()如果值不存在或缺失，则返回True\n",
    "  - notnull()如果值不存在或缺失，则返回False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ff2a744d-2542-4adf-adb1-98c9209b6146",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    False\n",
      "1    False\n",
      "2    False\n",
      "3     True\n",
      "dtype: bool\n",
      "0     True\n",
      "1     True\n",
      "2     True\n",
      "3    False\n",
      "dtype: bool\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "#None代表缺失数据\n",
    "s = pd.Series([1,2,5, None])\n",
    "print(pd.isnull(s))\n",
    "print(pd.notnull(s))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
